import React, { forwardRef, useState, useImperativeHandle, useRef, useEffect } from "react";
import { Form, Space, Radio, DatePicker, InputNumber, Select, Table, Button, Icon, Input } from '@bytedance/mona-ui';
import type { ColumnProps } from '@bytedance/mona-ui/es/components/table';
import './addStyle.scss'
import moment from 'moment';
import 'moment/locale/zh-cn';
import { configFarMate, yureDateTime, selectAcTimeList } from './ltalpFunc'

const { RangePicker } = DatePicker;
const { Option } = Select


let selectNoterOldData = [{
    title: '3分钟',
    value: 3
}, {
    title: '5分钟',
    value: 5
}, {
    title: '10分钟',
    value: 10
}, {
    title: '15分钟',
    value: 15
}, {
    title: '30分钟',
    value: 30
}]


function AddItemMt(props, ref) {

    let selectNewType = [{
        name: '限时抢购',
        content: (<>
            <span>活动时间:小于等于96小时</span>
            <span>活动价格:小于等于近15天通过限时限量购工具创建的最低生效标价,给予强化的腰封氛围</span>
        </>),
        checked: true,
        key: 'LimitTime'
    }, {
        name: '限量抢购',
        content: (<>
            <span> 活动库存:小于等于1000件</span>
            <span> 活动价格:小于等于近15天通过限时限量购工具创建的最低生效标价,商详给予强化的腰封氛围</span>
        </>),
        checked: false,
        key: 'LimitQuantity'
    }, {
        name: '普通降价促销',
        content: (<>
            <span>活动时间:小于等于365天</span>
            <span>优惠力度:至少99折,C端以红色的活动价进行展示</span>
        </>),
        checked: false,
        key: 'OrdinaryTimeBuy'
    }]
    let selectOldType = [{
        name: '限时抢购',
        content: (<>
            <span>活动时间:≤7天</span>
            <span>优惠力度:至少95折</span>
        </>),
        checked: true,
        key: '0'
    }, {
        name: '普通降价促销',
        content: (<>
            <span>活动时间:小于等于365天</span>
            <span>优惠力度:至少99折,C端以红色的活动价进行展示</span>
        </>),
        checked: false,
        key: 'OrdinaryTimeBuy'
    }]
    let { activetConfiginfo, onChangeItem, indexItem, onDeleteImageItem, editLtalpStatus } = props
    if (!activetConfiginfo) return
    const [addLtaLpConfig, setAddLtaLpConfig] = useState(activetConfiginfo)
    const [addActivetList, setAddActivetList] = useState(selectNewType)

    const {
        business_code,
        activetTypeSelect,
        selectTitlDater,
        selectAcTime,
        selectGetProdectListType,
        selectGetTimeData,
        selectNoteOrderTime,
        isKuscuetser,
        addActivetior,
        addActivetiorBc,
        setyufolyer,
        yusretimeData,
        showAll,
        endTimeSmit,
        endTimeTmetr,
        activtiTime,
        activetiQuantity,
        activetTimeBuy,
        activetName,
        activetNameTitel,

        begin_time, //开始时间
        end_time, //结束时间
        pre_begin_time, // 预热时间 在选择的时间后面加入
        order_expire_time, // 订单过期时间
        sold_out_type // 库存售罄0恢复原价后继续售卖 1停止售卖
    } = addLtaLpConfig
    useEffect(() => {

        // if (activetConfiginfo !== addLtaLpConfig) {
        //     setAddLtaLpConfig({ ...activetConfiginfo })
        // }
        return
    }, [activetConfiginfo])
    useEffect(() => {
        if (activetConfiginfo !== addLtaLpConfig) {

            onChangeItem && onChangeItem(configFarMate(addLtaLpConfig))
        }
    }, [addLtaLpConfig])
    useEffect(() => {
        const getSelectKey = addActivetList.find(item => item.checked)
        if (getSelectKey && getSelectKey.key !== business_code) {
            addLtaLpConfig.business_code = getSelectKey.key
            // activetConfiginfo = addLtaLpConfig
            setAddLtaLpConfig({
                ...addLtaLpConfig
            })
        }

    }, [addActivetList])
    function disabledDate(current) {
        return current && current < moment().subtract(1, 'days') || current > moment().add(7, 'days');
    }
    function disabledDateQter(current) {
        return current && current < moment().subtract(1, 'days') || current > moment().add(365, 'days');
    }
    interface ColumnPropsType {
        index: number;
        name: string;
    }
    const selectConfigTable: ColumnProps<ColumnPropsType>[] = [{
        title: '序号',
        key: '0',
        align: "center",
        render: (text: any, record: any, index: number) => {
            return `活动 ${indexItem + 1}`
        }
    },
    {
        title: '活动类型',
        key: '1',
        align: "center",
        width: 150,
        render: (text: any, record: any, index: number) => {
            // ? '(旧)' : '(新)'}{addActivetList.find(item => item.key === business_code)?.name
            return (<>{record.activetName}</>)
        }
    },
    {
        title: '生效条件',
        key: '2',
        align: "center",
        render: (text: any, record: any, index: number) => {
            return record.selectGetProdectListType ? '仅直播' : '活动期间'
        }
    },
    {
        title: '活动时间',
        key: '3',
        align: "center",
        render: (text: any, record: any, index: number) => {
            if (!record.begin_time || !record.end_time) return null


            return (
                <Space direction="vertical" size={2}>
                    <span>{record.begin_time}</span>
                    <span>{record.end_time}</span>
                </Space>)
        }
    },
    {
        title: '持续时间',
        key: '15',
        align: "center",
        render: (text: any, record: any, index: number) => {
            if (!record.begin_time || !record.end_time) return null

            const endater = moment.duration(moment(record.end_time).unix() - moment(record.begin_time).unix(), 'seconds')
            const d = endater.days()
            const h = endater.hours()
            const m = endater.minutes()
            const s = endater.seconds()

            return (`${d ? d + '天' : ''}${h ? h + '小时' : ''}${m ? m + '分钟' : ''}${s ? s + '秒' : ''}`)
        }
    },
    {
        title: '订单取消时间',
        key: '5',
        align: "center",
        render: (text: any, record: any, index: number) => {
            return record.selectNoteOrderTime + '分钟'
        }
    },
    {
        title: '库存售罄',
        key: '6',
        align: "center",
        render: (text: any, record: any, index: number) => {
            if (business_code === 'OrdinaryTimeBuy') {
                return isKuscuetser ? (record.addActivetior ? '停售，标示“已抢光”' : '恢复原价') : '不限库存'
            } else {
                return record.addActivetior ? '停售，标示“已抢光”' : '恢复原价'
            }

        }
    },
    {
        title: '预热',
        key: '7',
        align: "center",
        render: (text: any, record: any, index: number) => {
            // if(!yureDateTime) return null
            return business_code === 'OrdinaryTimeBuy' ? '/' : (record.setyufolyer ? `预热 ${yureDateTime.find(item => item.value === record.yusretimeData)?.title}` : '不预热')
        }
    },
    {
        title: '操作',
        key: '9',
        align: "center",
        render: (text: any, record: any, index: number) => {
            return (<Space>
                <Space>
                    <Button type="link" icon={<Icon type={record.showAll ? "DirectionUpIcon" : "DirectionDownIcon"}></Icon>} onClick={() => {
                        setAddLtaLpConfig({
                            ...addLtaLpConfig,
                            showAll: !record.showAll
                        })
                    }}>{record.showAll ? '收起' : '展开'}</Button>
                </Space>
                {/* <Space>
                    <Button type="link" disabled={editLtalpStatus.status} style={{ color: '#F11717' }} icon={<Icon type="DeleteIcon"></Icon>} onClick={() => {
                        onDeleteImageItem && onDeleteImageItem(indexItem)
                    }}>删除</Button>
                </Space> */}
            </Space>)
        }
    }
    ]
    return (<div>
        <div className="ActivetiStatusBox">
            <Table size="small" columns={selectConfigTable} dataSource={[addLtaLpConfig]} pagination={false} rowKey="business_code"></Table>
        </div>
        {showAll && <Form
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 24 }}
            layout="horizontal"
            name="couponConfig"
            initialValues={addLtaLpConfig}
        >
            <Form.Item
                label={(<Space direction="vertical">
                    <span>活动类型</span>
                    {false && <Radio.Group size="small" defaultValue={activetTypeSelect} onChange={(e) => {
                        if (e.target.value === 0) {
                            setAddActivetList([...selectNewType])
                        } else {
                            setAddActivetList([...selectOldType])
                        }
                        setAddLtaLpConfig({ ...addLtaLpConfig, activetTypeSelect: e.target.value })
                    }}>
                        <Radio value={0}>新版</Radio>
                        <Radio value={1}>旧版</Radio>
                    </Radio.Group>}
                </Space>)}
            >
                <Space wrap>
                    {addActivetList.map((item, key) => {
                        return <div className={item.checked ? "activetiConternt activetiConterntactive" : "activetiConternt"} key={key} onClick={() => {
                            addActivetList.forEach(item => {
                                item.checked = false
                            })
                            item.checked = true
                            if (activetTypeSelect === 0) {
                                selectNewType = [...addActivetList]
                            } else {
                                selectOldType = [...addActivetList]
                            }
                            // addLtaLpConfig.business_code = item.key
                            setAddLtaLpConfig({ ...addLtaLpConfig, business_code: item.key })
                            setAddActivetList([...addActivetList])

                        }}>
                            <Space direction="vertical" size={8}>
                                <div className="titconte">{item.name}</div>
                                <div className="addContent">{item.content}</div>
                                {item.checked && <div className="selectIcon">
                                    <svg width="26" height="24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M22 0H0l26 23.78V4a4 4 0 00-4-4z" fill="#1966FF"></path><path d="M14.648 6.881a.909.909 0 00-1.265 0 .862.862 0 000 1.238l2.684 2.625a.909.909 0 001.265 0l5.368-5.25a.861.861 0 000-1.238.909.909 0 00-1.265 0L16.7 8.888 14.648 6.88z" fill="#fff"></path></svg>
                                </div>}
                            </Space>
                        </div>
                    })}
                </Space>
            </Form.Item>

            <Form.Item
                name="couponAfterText"
                label="活动名称前缀">
                <Input maxLength={6} placeholder="可添加活动前缀名称" value={activetNameTitel} onChange={(e) => {
                    // addCouponConfig.couponAfterText = e.target.value.slice(0, 5)
                    setAddLtaLpConfig({ ...addLtaLpConfig, activetNameTitel: e.target.value.slice(0, 6) })
                }} style={{
                    width: 250
                }}></Input>
            </Form.Item>
            <Form.Item
                label="活动生效条件"
                extra={selectGetProdectListType ? '专属优惠仅在达人直播期间生效（适用直播、短视频、橱窗等），非直播期间此优惠无效' : '活动期间内达人渠道（直播间、短视频、橱窗等）均有可能以此优惠成交，不受直播与否影响，请谨慎设置'}
            >
                <Radio.Group size="small" defaultValue={selectGetProdectListType} onChange={(e) => {
                    setAddLtaLpConfig({ ...addLtaLpConfig, selectGetProdectListType: e.target.value })
                }}>
                    <Radio value={0}>活动期间均生效</Radio>
                    <Radio value={1}>仅直播期间生效</Radio>
                </Radio.Group>
            </Form.Item>
            {business_code === 'LimitTime' && (<>
                <Form.Item
                    label="活动开始时间"
                >
                    <DatePicker
                        format="YYYY-MM-DD HH:mm:ss"
                        disabledDate={disabledDate}
                        value={moment(activtiTime)}
                        allowClear={false}
                        // disabledTime={disabledDateTime}
                        showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                        onChange={(e) => {

                            setAddLtaLpConfig({ ...addLtaLpConfig, activtiTime: e })
                        }}
                    />
                </Form.Item>
                <Form.Item
                    label="持续时间"
                    extra={`仅支持输入正整数，最长持续时长为${selectTitlDater ? '59分钟' : '96小时'}`}
                >
                    <Space direction="vertical">
                        <Radio.Group size="small" defaultValue={selectTitlDater} onChange={(e) => {

                            setAddLtaLpConfig({ ...addLtaLpConfig, selectTitlDater: e.target.value })

                        }}>
                            <Radio value={0}>按小时持续</Radio>
                            <Radio value={1}>按分钟持续</Radio>

                        </Radio.Group>
                        <InputNumber min={1} max={selectTitlDater ? 59 : 96} unit={selectTitlDater ? '分' : '时'} value={selectTitlDater ? endTimeTmetr : endTimeSmit} onChange={(e) => {

                            selectTitlDater ? setAddLtaLpConfig({ ...addLtaLpConfig, endTimeTmetr: e }) : setAddLtaLpConfig({ ...addLtaLpConfig, endTimeSmit: e })
                        }}></InputNumber>
                    </Space>
                </Form.Item>
            </>)}
            {business_code === 'LimitQuantity' && <Form.Item
                label="活动时间"
            >
                <RangePicker
                    disabledDate={disabledDate}
                    // disabledTime={disabledRangeTime}
                    ranges={{
                        '1天内': [moment(), moment().add(1, 'days')],
                        '今晚0点一天内': [moment().add(1, 'day').startOf('day'), moment().add(2, 'day').startOf('day').subtract(1, 'second')],
                        '3天内': [moment(), moment().add(3, 'days')],
                        '今晚0点三天内': [moment().add(1, 'day').startOf('day'), moment().add(4, 'day').startOf('day').subtract(1, 'second')],
                        '一周内': [moment(), moment().add(7, 'days')],
                        '今晚0点一周内': [moment().add(1, 'day').startOf('day'), moment().add(8, 'day').startOf('day').subtract(1, 'second')],
                    }}
                    showTime={{
                        hideDisabledOptions: true,
                        defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
                    }}
                    allowClear={false}
                    format="YYYY-MM-DD HH:mm:ss"
                    value={[moment(activetiQuantity[0]), moment(activetiQuantity[1])]}
                    onChange={(e) => {

                        setAddLtaLpConfig({ ...addLtaLpConfig, activetiQuantity: e })
                        // moment().format('YYYY-MM-DD HH:mm:ss')
                        // setAddLtaLpConfig({ ...addLtaLpConfig, selectTime: e })

                    }}
                />
            </Form.Item>}

            {(business_code === 'OrdinaryTimeBuy' || business_code === '0') && <Form.Item
                label="活动时间"
            // help={}
            // extra={`仅支持输入正整数，最长持续时长为${selectTitlDater ? '59分钟' : '48小时'}`}
            >
                <Space direction="vertical">
                    <Radio.Group size="small" defaultValue={selectAcTime} onChange={(e) => {
                        // setSelectAcTime(e.target.value)
                        setAddLtaLpConfig({ ...addLtaLpConfig, selectAcTime: e.target.value })

                    }}>
                        <Radio value={0}>按开始结束时间设置</Radio>
                        <Radio value={1}>按时间段选择</Radio>

                    </Radio.Group>
                    {selectAcTime ? <Space>
                        <span style={{
                            color: '#55585c',
                            fontSize: 14
                        }}>活动持续</span>
                        <Select style={{ width: 220 }} value={selectGetTimeData} onChange={(e: any) => {
                            // setSelectGetTimeData(e)
                            setAddLtaLpConfig({ ...addLtaLpConfig, selectGetTimeData: e })

                        }} >
                            {selectAcTimeList.map(item => {
                                return <Option value={item.value} key={item.value}>{item.title}</Option>
                            })}
                        </Select>
                        <span style={{
                            color: '#aaabaf',
                            fontSize: 12
                        }}>后结束（创建成功后，活动立即生效）</span>

                    </Space> : <RangePicker
                        disabledDate={disabledDateQter}
                        // disabledTime={disabledRangeTime}
                        ranges={{
                            '1天内': [moment(), moment().add(1, 'days')],
                            '今晚0点一天内': [moment().add(1, 'day').startOf('day'), moment().add(2, 'day').startOf('day').subtract(1, 'second')],
                            '3天内': [moment(), moment().add(3, 'days')],
                            '今晚0点三天内': [moment().add(1, 'day').startOf('day'), moment().add(4, 'day').startOf('day').subtract(1, 'second')],
                            '一周内': [moment(), moment().add(7, 'days')],
                            '今晚0点一周内': [moment().add(1, 'day').startOf('day'), moment().add(8, 'day').startOf('day').subtract(1, 'second')],
                        }}
                        value={[moment(activetTimeBuy[0]), moment(activetTimeBuy[1])]}
                        allowClear={false}
                        showTime={{
                            hideDisabledOptions: true,
                            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')],
                        }}
                        format="YYYY-MM-DD HH:mm:ss"
                        onChange={(e) => {
                            if (e) {
                                const endater = moment.duration(e[1].unix() - e[0].unix(), 'seconds')
                                console.log('endater')
                                const d = endater.days()
                                const h = endater.hours()
                                const m = endater.minutes()
                                const s = endater.seconds()
                                console.log(d, h, m, s)

                                if (d > 365) {
                                    console.log('活动时间太长')
                                }
                                if (d == 365 && (h > 0 || m > 0 || s > 0)) {
                                    console.log('活动时间太长')
                                }
                            }
                            setAddLtaLpConfig({ ...addLtaLpConfig, activetTimeBuy: e })
                        }}
                    />}

                </Space>
            </Form.Item>}

            <Form.Item
                label="订单取消时间"
                extra="活动的订单取消时间建议设置为5分钟"
            >
                <Select style={{ width: 220 }} value={selectNoteOrderTime} onChange={(e: any) => {
                    // setSelectNoteOrderTime(e)
                    setAddLtaLpConfig({ ...addLtaLpConfig, selectNoteOrderTime: e })

                }} >
                    {selectNoterOldData.map(item => {
                        return <Option value={item.value} key={item.value}>{item.title}</Option>
                    })}
                </Select>
            </Form.Item>

            {business_code === 'OrdinaryTimeBuy' && <Form.Item
                label="是否设置活动库存"
            ><Space direction="vertical">
                    <Radio.Group size="small" defaultValue={isKuscuetser} onChange={(e) => {
                        // setIsKuscuetser(e.target.value)
                        setAddLtaLpConfig({ ...addLtaLpConfig, isKuscuetser: e.target.value })

                    }}>
                        <Radio value={0}>不限活动库存</Radio>
                        <Radio value={1}>限活动库存</Radio>
                    </Radio.Group>
                    {!!isKuscuetser && <Form.Item
                        label="活动库存售罄"
                    >
                        <Radio.Group size="small" defaultValue={addActivetior} onChange={(e) => {
                            // setAddActivetior(e.target.value)
                            setAddLtaLpConfig({ ...addLtaLpConfig, addActivetior: e.target.value })

                        }}>
                            <Radio value={0}>恢复为原价继续售卖</Radio>
                            <Radio value={1}>停止售卖，商品标示“已抢光”</Radio>
                        </Radio.Group>
                    </Form.Item>}
                </Space>
            </Form.Item>}
            {/* {business_code === '0' && <Form.Item
                label="活动库存售罄"
            >
                <Radio.Group size="small" defaultValue={addActivetior} onChange={(e) => {
                    // setAddActivetior(e.target.value)
                    // setAddLtaLpConfig({ ...addLtaLpConfig, addActivetior: e.target.value })

                }}>
                    <Radio value={0}>恢复为原价继续售卖</Radio>
                    <Radio value={1}>停止售卖，商品标示“已抢光”</Radio>
                </Radio.Group>
            </Form.Item>} */}
            {business_code !== 'OrdinaryTimeBuy' && (<>
                <Form.Item
                    label="活动库存售罄"
                >
                    <Radio.Group size="small" defaultValue={addActivetiorBc} onChange={(e) => {
                        // setAddActivetiorBc(e.target.value)
                        setAddLtaLpConfig({ ...addLtaLpConfig, addActivetiorBc: e.target.value })

                    }}>
                        <Radio value={0}>恢复为原价继续售卖</Radio>
                        <Radio value={1}>停止售卖，商品标示“已抢光”</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item
                    label="预热"
                ><Space direction="vertical">
                        <Radio.Group size="small" defaultValue={setyufolyer} onChange={(e) => {
                            // setSetyufolyer(e.target.value)
                            setAddLtaLpConfig({ ...addLtaLpConfig, setyufolyer: e.target.value })

                        }}>
                            <Radio value={0}>不预热</Radio>
                            <Radio value={1}>预热</Radio>
                        </Radio.Group>
                        {!!setyufolyer && (<Space>
                            <span style={{
                                color: '#55585c',
                                fontSize: 14
                            }}>活动开始前</span>
                            <Select style={{ width: 220 }} value={yusretimeData} onChange={(e: any) => {
                                // setYusretimeData(e)
                                setAddLtaLpConfig({ ...addLtaLpConfig, yusretimeData: e })

                            }} >
                                {yureDateTime.map(item => {
                                    return <Option value={item.value} key={item.value}>{item.title}</Option>
                                })}
                            </Select>
                            <span style={{
                                color: '#55585c',
                                fontSize: 14
                            }}>进行预热</span>

                        </Space>)}
                    </Space>
                </Form.Item>
            </>)
            }

        </Form>}
    </div>)
}

export default forwardRef(AddItemMt)